Page({
  data: {
    musics: [
      {
        id: 1,
        src:
          "http://218.205.239.34/MIGUM2.0/v1.0/content/sub/listenSong.do?netType=00&copyrightId=0&resourceType=2&contentId=600902000009525578&toneFlag=LQ&channel=02", // 歌曲资源
        title: "美人鱼 - 林俊杰", // 歌曲名称
        coverImgUrl:
          "http://d.musicapp.migu.cn/prod/file-service/file-down01/8121e8df41a5c12f48b69aea89b71dab/00f4563b7eaad0bd70d8f4e413e4d342/21214bce92c1774b72d2d7491b12395d", // 封面图
      },
      {
        id: 2,
        src:
          "http://218.205.239.34/MIGUM2.0/v1.0/content/sub/listenSong.do?netType=00&copyrightId=0&resourceType=2&contentId=600919000005413980&toneFlag=LQ&channel=02", // 歌曲资源
        title: "孤勇者 - 林俊杰", // 歌曲名称
        coverImgUrl:
          "http://d.musicapp.migu.cn/prod/file-service/file-down/8121e8df41a5c12f48b69aea89b71dab/ec2ab264dda5e4a87346f5002571ecef/aea3c247a293c47f67b018785a72a6b7", // 封面图
      },
    ],
    curMusicIndex: 0,
    step: 0,
    currentTime: "00:00",
    totalTime: "00:00",
  },
  totalSeconds: 0,
  bgManager: {} as WechatMiniprogram.BackgroundAudioManager,
  onLoad() {
    // wx.hideTabBar({}); // 隐藏tabbar
    // wx.showTabBarRedDot({
    //   index: 2,
    // }); // 设置某个tabbar选项的小红点
    wx.setTabBarBadge({
      index: 2,
      text: "10",
    }); // 设置某个tabbar右上角文本

    // 初始化请求
    // wx.request({
    //   url:
    //     "https://m.lanqb.com/api/daniu?link=paging&live=3&is_live=1&limit=3&page=1",
    //   success: (data) => {
    //     console.log(data.data);
    //   },
    // });

    // 创建背景音频播放器对象
    this.bgManager = wx.getBackgroundAudioManager();
    // 监听音频播放事件，持续触发。
    this.bgManager.onTimeUpdate(() => {
      const curTime = this.bgManager.currentTime;
      const duration = this.bgManager.duration;
      console.log(
        "---",
        curTime,
        duration,
        parseInt(`${(curTime / duration) * 100}`)
      );
      this.setData({
        step: parseInt(`${(curTime / duration) * 100}`),
        currentTime: this.formatTime(curTime),
      });
    });
    // 监听音频开始播放的事件，只执行一次。
    this.bgManager.onPlay(() => {
      // const curTime = this.bgManager.currentTime;
      // const duration = this.bgManager.duration;
      // this.totalSeconds = duration;
      // console.log("===", curTime, duration);
      // this.setData({
      //   currentTime: this.formatTime(curTime),
      //   totalTime: this.formatTime(duration),
      // });
    });
    // 监听歌曲播放结束事件
    this.bgManager.onEnded(() => {
      if (this.data.curMusicIndex === this.data.musics.length - 1) {
        // 此时播放结束是最后一首
        this.setData({
          curMusicIndex: 0,
        });
      } else {
        this.setData({
          curMusicIndex: this.data.curMusicIndex + 1,
        });
      }
      this.setMusic();
    });
    // 监听音频缓冲事件
    this.bgManager.onWaiting(() => {
      wx.showToast({
        title: "网络较慢...",
        icon: "none",
      });
    });
    // 监听音频资源可以播放了，缓冲了一定的数据时，可以播放了，不保证后面流畅播放
    this.bgManager.onCanplay(() => {
      const curTime = this.bgManager.currentTime;
      const duration = this.bgManager.duration;
      this.totalSeconds = duration;
      // console.log("===", curTime, duration);
      this.setData({
        currentTime: this.formatTime(curTime),
        totalTime: this.formatTime(duration),
      });
      wx.hideToast();
    });
    this.setMusic();
  },
  onShow() {
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2,
      });
    }
  },
  formatTime(seconds: number): string {
    // 将总秒数，转化为 分:秒 的形式
    let sec: number | string = parseInt(`${seconds % 60}`);
    sec = sec < 10 ? "0" + sec : sec + "";
    let min: number | string = parseInt(`${seconds / 60}`);
    min = min < 10 ? "0" + min : min + "";
    return `${min}:${sec}`;
  },
  setMusic() {
    const curMusic = this.data.musics[this.data.curMusicIndex];
    this.bgManager.src = curMusic.src;
    this.bgManager.title = curMusic.title;
    this.bgManager.coverImgUrl = curMusic.coverImgUrl;
    this.bgManager.play();
  },
  showToast() {
    wx.showToast({
      title: "成功",
      mask: true,
      icon: "none",
    });
  },
  showloading() {
    wx.showLoading({
      title: "加载中",
    });
    setTimeout(function () {
      wx.hideLoading();
    }, 1000);
  },
  setNavTitle() {
    wx.setNavigationBarTitle({
      title: "我是导航",
    });
  },
  // onPullDownRefresh：小程序内置函数，监听用户的下拉动作。
  onPullDownRefresh() {
    wx.showLoading({
      title: "加载中...",
    });
    setTimeout(() => {
      console.log("请求数据成功");
      wx.hideLoading();
      wx.stopPullDownRefresh(); // 停止下拉动作
    }, 1000);
  },
  chooseImage() {
    wx.chooseMedia({
      count: 9,
      mediaType: ["image", "video"],
      sourceType: ["album", "camera"],
      maxDuration: 30,
      camera: "back",
      success(res: any) {
        console.log(res);
      },
    });
  },
  changeMusic(e: IEvent) {
    this.setData({
      curMusicIndex: e.target.dataset.idx,
    });
    this.setMusic();
  },
  changeSlider(e: IEvent) {
    const curStep = e.detail.value;
    this.setData({
      step: curStep,
    });
    this.bgManager.seek((curStep / 100) * this.totalSeconds);
  },
});
